package info.androidhive.pratap;

import info.androidhive.pratap.models.Product;
import info.androidhive.volleyexamples.R;
import info.androidhive.volleyexamples.app.AppController;
import info.androidhive.volleyexamples.volley.utils.Const;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ProductsListViewActivity extends Activity {

	private String TAG = ProductsListViewActivity.class.getSimpleName();
	private ListView dataListView;
	private ProgressDialog pDialog;

	private List<Product> allProducts = new ArrayList<Product>();

	// These tags will be used to cancel the requests
	private String tag_json_obj = "jobj_req", tag_json_arry = "jarray_req";
	private JSONArray jsonProuctsArray;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.customlistview_activity);

		dataListView = (ListView) findViewById(R.id.dataListView);

		pDialog = new ProgressDialog(this);
		pDialog.setMessage("Loading...");
		pDialog.setCancelable(false);

	//	makeJsonObjReq();
		makeJsonArryReq();

	}

	/**
	 * Making json object request
	 * */
	private void makeJsonObjReq() {
		showProgressDialog();
		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
				Const.GET_ALL_DROPBOX_PRODUCTS1, null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						Log.d(TAG, response.toString());

						// parseProducts(response);

						parseProductsGson(response.toString());

						hideProgressDialog();
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						VolleyLog.d(TAG, "Error: " + error.getMessage());
						hideProgressDialog();
					}
				}) {

			/**
			 * Passing some request headers
			 * */
			/*
			 * @Override public Map<String, String> getHeaders() throws
			 * AuthFailureError { HashMap<String, String> headers = new
			 * HashMap<String, String>(); headers.put("Content-Type",
			 * "application/json"); return headers; }
			 */

		};

		// Adding request to request queue
		AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

		// Cancelling request
		// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
	}

	
	/**
	 * Making json array request
	 * */
	private void makeJsonArryReq() {
		showProgressDialog();
		JsonArrayRequest req = new JsonArrayRequest(Const.GET_ALL_DROPBOX_PRODUCTS1,
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						Log.d(TAG, response.toString());
						parseProductsGson(response.toString());
						hideProgressDialog();
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						VolleyLog.d(TAG, "Error: " + error.getMessage());
						hideProgressDialog();
					}
				});

		// Adding request to request queue
		AppController.getInstance().addToRequestQueue(req,
				tag_json_arry);

		// Cancelling request
		// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_arry);
	}
	
	protected void parseProductsGson(String jsonString) {
		Gson gson = new Gson();
		Type collectionType = new TypeToken<List<Product>>() {
		}.getType();
		allProducts = gson.fromJson(jsonString, collectionType);

		ProductsAdapter padapter = new ProductsAdapter(this, allProducts);
		dataListView.setAdapter(padapter);

	}

	protected void parseProducts(JSONObject jsonobj) {

		try {

	//		String json = jsonobj.toString();

			jsonProuctsArray = jsonobj.getJSONArray("products");

			if (jsonProuctsArray != null) {
				// looping through All albums
				for (int i = 0; i < jsonProuctsArray.length(); i++) {
					JSONObject c = jsonProuctsArray.getJSONObject(i);

					// Storing each json item values in variable
					String pid = c.getString("pid");
					String pname = c.getString("pname");
					String price1 = c.getString("price1");

					// Creating object for each product
					Product singleProduct = new Product(Integer.valueOf(pid),
							pname, Float.valueOf(price1));

					// adding HashList to ArrayList
					allProducts.add(singleProduct);

				}

				ProductsAdapter padapter = new ProductsAdapter(this,
						allProducts);
				dataListView.setAdapter(padapter);
			} else {
				Log.d("Products: ", "null");
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void showProgressDialog() {
		if (!pDialog.isShowing())
			pDialog.show();
	}

	private void hideProgressDialog() {
		if (pDialog.isShowing())
			pDialog.hide();
	}

	private void dismissProgressDialog() {
		if (pDialog != null)
			pDialog.dismiss();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		dismissProgressDialog();

	}

}
